package top.xia17.plugins.fast.auth.rest;

import cn.hutool.core.util.IdUtil;
import top.xia17.plugins.fast.common.model.Back;
import top.xia17.plugins.fast.common.database.redis.RedisUtils;
import top.xia17.plugins.fast.common.security.anonymous.AnonymousGetMapping;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xia17.plugins.fast.auth.captcha.CaptchaUtil;
import top.xia17.plugins.fast.auth.model.resp.CaptchaResp;

import java.util.concurrent.TimeUnit;

/**
 * 验证码接口
 *
 * @author xia17
 * @date 2022/4/7
 */
@RestController
@RequestMapping("captcha")
@RequiredArgsConstructor
public class CaptchaRest {

    private final CaptchaUtil captchaUtil;
    private final RedisUtils redisUtils;

    /**
     * 获取图形验证码
     * 该接口可在其他需要验证码的地方使用
     *
     * @return /
     */
    @AnonymousGetMapping("img")
    public Back<CaptchaResp> getImgCaptcha() {
        Captcha captcha = captchaUtil.createCaptcha();
        String uuid = captchaUtil.getCaptchaProperties().getUuidPrefix() + IdUtil.simpleUUID();
        String captchaValue = CaptchaUtil.getText(captcha);
        // 保存到redis
        redisUtils.set(uuid, captchaValue, captchaUtil.getCaptchaProperties().getExpiration(), TimeUnit.MINUTES);
        CaptchaResp resp = new CaptchaResp(uuid, captcha.toBase64());
        return Back.ok(resp);
    }


}
